import React, { useCallback, useEffect, useState } from 'react';
import { BellOutlined, LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { Badge, Menu, Spin } from 'antd';
import { getDvaApp, history, useModel } from 'umi';
import { stringify } from 'querystring';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import type { MenuInfo } from 'rc-menu/lib/interface';
import $utils from '@/utils/utils';
import { getTodoCount } from '@/services/feedback';

export type GlobalHeaderRightProps = {
    menu?: boolean;
};

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
    const { query = {}, search, pathname } = history.location;
    const { redirect } = query;
    $utils.removeAllStorage();
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
            pathname: '/user/login',
            search: stringify({
                redirect: pathname + search,
            }),
        });
    }
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
    const { initialState, setInitialState } = useModel('@@initialState');

    const [noReplyCount, setNoReplyCount] = useState<any>(0);

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;

    const onMenuClick = useCallback(
        (event: MenuInfo) => {
            const { key } = event;
            if (key === 'logout') {
                setInitialState((s) => ({ ...s, currentUser: undefined }));
                loginOut();
                return;
            }
            history.push(`/account/${key}`);
        },
        [setInitialState],
    );

    useEffect(() => {
        const getCount = async () => {
            try {
                const msg = await getTodoCount({});
                if (msg.code === 0) {
                    setNoReplyCount(msg.body?.todoCount || 0);
                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };

        getCount();
    })

    const loading = (
        <span className={`${styles.action} ${styles.account}`}>
            <Spin
                size="small"
                style={{
                    marginLeft: 8,
                    marginRight: 8,
                }}
            />
        </span>
    );

    if (!initialState) {
        return loading;
    }

    const { currentUser } = initialState;

    if (!currentUser || !currentUser.name) {
        return loading;
    }

    const menuHeaderDropdown = (
        <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
            {menu && (
                <Menu.Item key="center">
                    <UserOutlined />
                    个人中心
                </Menu.Item>
            )}
            {menu && (
                <Menu.Item key="settings">
                    <SettingOutlined />
                    个人设置
                </Menu.Item>
            )}
            {menu && <Menu.Divider />}

            <Menu.Item key="logout">
                <LogoutOutlined />
                退出登录
            </Menu.Item>
        </Menu>
    );
    return (
        <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center' }}>
            <Badge size={'small'} count={noReplyCount} >
                <BellOutlined style={{ fontSize: 18, cursor: 'pointer', marginRight: '6px' }} onClick={() => {
                    // 设置当前tab对象
                    $utils.setNewTab(dispatch, { name: '意见反馈', path: '/OperationsMange/Feedback', isTopMenu: true });
                    $utils.addTab(dispatch, {
                        name: '意见反馈',
                        path: '/OperationsMange/Feedback',
                        isTopMenu: true,
                    });
                    history.push({
                        pathname: '/OperationsMange/Feedback',
                    });
                }} />
            </Badge>
            <HeaderDropdown overlay={menuHeaderDropdown}>
                <span className={`${styles.action} ${styles.account}`}>
                    {/* <Avatar size="small" className={styles.avatar} src={currentUser?.avatar} alt="avatar" /> */}
                    <span className={`${styles.name} anticon`}>
                        <span style={{ marginRight: 12 }}>{currentUser.phone}</span>
                        {currentUser.name}
                    </span>
                </span>
            </HeaderDropdown>
        </div>

    );
};

export default AvatarDropdown;
